package cn.dwj.hadoop.mr.ii;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * Created by Administrator on 2017/12/29 0029.
 */
public class InverseIndexStepOne {
    public static class SteOneMapper extends Mapper<LongWritable, Text, Text, LongWritable>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            //拿到一行数据
            String line = value.toString();
            String[] fields = StringUtils.split(line, "\t");

            //获取这一行数据所在的文件切片
            FileSplit inputSplit = (FileSplit) context.getInputSplit();
            //从文件切片中获取文件名
            String fileName = inputSplit.getPath().getName();

            for(String field : fields){
                //封装kv输出
                context.write(new Text(field+"-->"+fileName), new LongWritable(1));
            }
        }
    }

    public static class SteOneReduce extends Reducer<Text, LongWritable, Text, LongWritable>{
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long count = 0;
            for(LongWritable value : values){
                count = count + value.get();
            }

            context.write(key, new LongWritable(count));
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);
        //设置整个job所在的那些类在哪个jar包中
        job.setJarByClass(InverseIndexStepOne.class);
        //本job使用的map和reduce的类
        job.setMapperClass(SteOneMapper.class);
        job.setReducerClass(SteOneReduce.class);

        //指定输出数据的类型，对mapper和reduce的类型都起作用
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        FileInputFormat.setInputPaths(job, new Path[]{new Path("")});
        Path output = new Path("");
        FileSystem fs = FileSystem.get(conf);
        if(fs.exists(output)){
            fs.delete(output, true);
        }
        FileOutputFormat.setOutputPath(job, output);//指定处理结果输出数据存放在路径

        System.exit(job.waitForCompletion(true)?0:1); //将job提交给集群运行过程要不要提示出来
    }
}
